package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.forms.AutoSiteForm;
import admin.models.AutoSiteModel;
import admin.models.CategoryModel;

import entities.AutoSite;
import entities.Category;

public class AddSiteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		AutoSite autoSite = new AutoSite();
		TreeMap check = new TreeMap();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		request.setAttribute("check", check);
		request.setAttribute("autoSite", autoSite);
		request.setAttribute("form", "add");
		request.setAttribute("categories", categories);
		try {
            request.getRequestDispatcher("/admin/pages/form_site.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		AutoSiteModel autoData = AutoSiteModel.getInstance();
		AutoSite autoSite = new AutoSite();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		//Get value form and check valid
		TreeMap form = AutoSiteForm.checkValid(request, autoSite);
		autoSite =(AutoSite) form.get("autoSite");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			autoSite.setId(IdUniqueHelper.getId());
			autoData.insert(autoSite);
			request.setAttribute("success", "Add success site " + autoSite.getUrl());
			autoSite = new AutoSite();
		}
		
		request.setAttribute("check", check);
		request.setAttribute("autoSite", autoSite);
		request.setAttribute("form", "add");
		request.setAttribute("categories", categories);
		try {
	        request.getRequestDispatcher("/admin/pages/form_site.jsp").forward(request, response);
	    } catch (Exception e) {
	        //TODO: handle exception
	        e.printStackTrace();
	    }
	}
}
